package com.eascs.admin.o2o.backfee.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.controller.BaseViewController;
import com.eascs.admin.o2o.backfee.service.O2OComBankFeeService;
import com.eascs.admin.o2o.o2ozx.controller.O2oZxController;
import com.eascs.admin.oldO2olike.form.OldO2oLikeForm;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.doc.excel.DefaultRowWriteHandler;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.IoUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.tag.MenuTag;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.service.sys.SysOrgService;

@Controller
@RequestMapping("/bond")
public class O2oBondFeeController extends BaseViewController  {
	
	
	private final Logger logger = LoggerFactory.getLogger(O2oBondFeeController.class);
	
	public void preHandle() {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "loanManage1");
	}
	@Autowired
	O2OComBankFeeService o2oComBankFeeService;
	
	@Reference
	SysOrgService sysOrgService;
	
	@RequestMapping("/index")
	public String index(OldO2oLikeForm entity){
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "sfbond_liebiao");
		String o2oPageUrl = "/bond/index";
		entity.setPageSize(10);
		
		
		List<User> users=sysOrgService.checkDataPermission(UserHolder.getUser().getNo());
		String no="";
		if (users!=null) {
			for (User user : users) {
				no+=user.getNo()+",";
			}
		}
		if (!"".equals(no)) {
			if (",".equals(no.substring(no.length()-1, no.length()))) {
				no=no.substring(0, no.length()-1);
			}
		}
		logger.info("userno={}", no);
		entity.setXdjlNo(no);
		
		PageResult<Object[]> o2opageResult = o2oComBankFeeService.findSfbzjByPage(entity);
		String[] o2otitles = { "贷款单号", "借款人姓名", "贷款类型", "经办平台", "信贷经理","EA审批金额(万元)","送审银行","申请状态" ,"流程状态","创建时间" };
		Button[] findButton = new Button[] { ButtonHelper.createAjaxButton(null, "/rbond/detail?billCode="), null };
		SelectDataOption[] selectDataOptions = {null,null, new SelectDataOption("OTO_LOAN_TYPE"),null,null,null,new SelectDataOption("BANKTYPEO2O"), new SelectDataOption("SQZT"), new SelectDataOption("LCZT"), null };
		String backfeeReportUrl="/bond/bondExport";
		if (entity != null) {
			String loanType = entity.getLoanType() == null ? "" : entity.getLoanType();
			String billCode = entity.getBillCode()== null ? "" : entity.getBillCode();
			String userSurname = entity.getUserSurname() == null ? "" : entity.getUserSurname();
			String  spState= entity.getSpState() == null ? "" : entity.getSpState();
			String billStatus = entity.getBillStatus() == null ? "" : entity.getBillStatus();
			String start_time= entity.getStartTime() == null ? "" : entity.getStartTime();
			String end_time= entity.getEndTime() == null ? "" : entity.getEndTime();
			String payMentStatus=entity.getPayMentStatus()==null?"":entity.getPayMentStatus();
			
			o2oPageUrl = UrlUtil.appendUrl(o2oPageUrl, "loanType", loanType);
			o2oPageUrl = UrlUtil.appendUrl(o2oPageUrl, "billCode", billCode);
			o2oPageUrl = UrlUtil.appendUrl(o2oPageUrl, "userSurname", userSurname);
			o2oPageUrl = UrlUtil.appendUrl(o2oPageUrl, "billStatus", billStatus);
			o2oPageUrl = UrlUtil.appendUrl(o2oPageUrl, "spState", spState);
			o2oPageUrl = UrlUtil.appendUrl(o2oPageUrl, "start_time",start_time);
			o2oPageUrl = UrlUtil.appendUrl(o2oPageUrl, "end_time",end_time);
			o2oPageUrl = UrlUtil.appendUrl(o2oPageUrl, "payMentStatus",payMentStatus);
			
			backfeeReportUrl = UrlUtil.appendUrl(backfeeReportUrl, "loanType", loanType);
			backfeeReportUrl = UrlUtil.appendUrl(backfeeReportUrl, "billCode", billCode);
			backfeeReportUrl = UrlUtil.appendUrl(backfeeReportUrl, "userSurname", userSurname);
			backfeeReportUrl = UrlUtil.appendUrl(backfeeReportUrl, "billStatus", billStatus);
			backfeeReportUrl = UrlUtil.appendUrl(backfeeReportUrl, "spState", spState);
			backfeeReportUrl = UrlUtil.appendUrl(backfeeReportUrl, "start_time",start_time);
			backfeeReportUrl = UrlUtil.appendUrl(backfeeReportUrl, "end_time",end_time);
			backfeeReportUrl = UrlUtil.appendUrl(backfeeReportUrl, "payMentStatus",payMentStatus);
			
		}
		o2oPageUrl = o2oPageUrl + "&pageIndex=";
		PaginationInfo paginationInfo = new PaginationInfo(o2opageResult, o2otitles, o2oPageUrl);
		paginationInfo.setTitleButtons(findButton);
		paginationInfo.setSelectDataOptions(selectDataOptions);
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(0);
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("o2oPageUrl", o2oPageUrl);
		ViewContext.put("bondReportUrl", backfeeReportUrl);
		ViewContext.put("vo", entity);
		return "/bond/index";
	}
	
	@RequestMapping("/bondExport")
	public void bondExport(OldO2oLikeForm entity,HttpServletResponse httpServletResponse, HttpServletRequest request) {
		entity.setPageSize(Integer.MAX_VALUE);
		entity.setFlag("export");
		
		List<User> users=sysOrgService.checkDataPermission(UserHolder.getUser().getNo());
		String no="";
		if (users!=null) {
			for (User user : users) {
				no+=user.getNo()+",";
			}
		}
		if (!"".equals(no)) {
			if (",".equals(no.substring(no.length()-1, no.length()))) {
				no=no.substring(0, no.length()-1);
			}
		}
		logger.info("userno={}", no);
		entity.setXdjlNo(no);
		
		PageResult<Object[]> pageResult = o2oComBankFeeService.findSfbzjByPage(entity);
		String path = O2oComBackFeeController.class.getResource("/excelTemplate").getPath();
		StringBuffer s = new StringBuffer();
		String outPath = s.append(path).append("/bond-model.xls").toString();
		OutputStream os = null;
		try {
			String outfile = "收费查询列表.xls";
			String userAgent = request.getHeader("User-Agent");
			byte[] bytes = userAgent.contains("MSIE") ? outfile.getBytes() : outfile.getBytes("UTF-8");
			outfile = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
			File f = new File(outPath);
			if (!f.exists())
				throw new RuntimeIOException("file not found");
			os = httpServletResponse.getOutputStream();
			httpServletResponse.reset();
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + outfile);
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			DefaultRowWriteHandler defaultRowWriteHandler = new DefaultRowWriteHandler(pageResult.getData());
			ExcelApiHelper.writeHandle(httpServletResponse.getOutputStream(), O2oComBackFeeController.class.getResourceAsStream("/excelTemplate/bond-model.xls"), defaultRowWriteHandler);
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			IoUtil.fileToOutputStream(f, byteArrayOutputStream);
			os.write(byteArrayOutputStream.toByteArray());
			os.flush();
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		} finally {
			IoUtil.close(os);
		}
//		return result;
	}
	
	
		
	
	
}
